package Interview.pinduoduo;


import domain.ListNode;

/**
 * 给出两个链表 3->1->5->null 和 5->9->2->null，返回 8->0->8->null
 *
 * @author leiwenkang
 * @date 2020/4/4
 */
public class Test02链表相加 {
    public static void main(String[] args) {
        ListNode head1 = new ListNode(3);
        ListNode p11 = new ListNode(1);
        ListNode p12 = new ListNode(5);
        head1.next = p11;
        p11.next = p12;

        ListNode head2 = new ListNode(5);
        ListNode p21 = new ListNode(9);
        ListNode p22 = new ListNode(4);
        head2.next = p21;
        p21.next = p22;

        Test02链表相加 test02链表相加 = new Test02链表相加();
        ListNode head = test02链表相加.sumListNode(head1, head2);
        //打印结果
        test02链表相加.printListNode(head);
    }

    public ListNode sumListNode(ListNode head1, ListNode head2) {
        ListNode p1 = head1;
        ListNode p2 = head2;

        ListNode head = new ListNode(-1);
        ListNode p = head;
        int takeOver = 0;
        while (p1 != null || p2 != null) {
            int sum = takeOver;
            if (p1 != null) {
                sum += p1.val;
                p1 = p1.next;
            }

            if (p2 != null) {
                sum += p2.val;
                p2 = p2.next;
            }

            if (sum >= 10) {
                sum -= 10;
                takeOver = 1;
            } else {
                takeOver = 0;
            }
            p.next = new ListNode(sum);
            p = p.next;
        }
        if (takeOver == 1) {
            p.next = new ListNode(1);
        }
        return head.next;
    }

    private void printListNode(ListNode head) {
        ListNode p = head;
        while (p != null) {
            System.out.print(p.val);
            System.out.print(" ");
            p = p.next;
        }
    }


}
